package io.renren.modules.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.exception.RenException;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.DateUtils;
import io.renren.modules.customer.dto.CustomerInfoDTO;
import io.renren.modules.customer.service.CustomerInfoService;
import io.renren.modules.order.dao.OrderDao;
import io.renren.modules.order.dto.*;
import io.renren.modules.order.entity.OrderEntity;
import io.renren.modules.order.entity.OrderPaymentEntity;
import io.renren.modules.order.excel.OrderExcel;
import io.renren.modules.order.service.OrderContractService;
import io.renren.modules.order.service.OrderPaymentService;
import io.renren.modules.order.service.OrderService;
import cn.hutool.core.util.StrUtil;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysRoleUserService;
import io.renren.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-12-07
 */
@Slf4j
@Service
public class OrderServiceImpl extends CrudServiceImpl<OrderDao, OrderEntity, OrderDTO> implements OrderService {

    /**
     * 上传图片和图稿资源路径
     */
    @Value("${upload.path}")
    private String path;
    /**
     * 上传图片和图稿资源路径
     */
    @Value("${upload.uploads}")
    private String uploadsPath;

    @Value("${fileUrl}")
    private String fileUrl;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private OrderContractService orderContractService;

    @Autowired
    private OrderPaymentService orderPaymentService;

    @Override
    public QueryWrapper<OrderEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String customerId = (String)params.get("customerId");
        String serviceItem = (String)params.get("serviceItem");
        String introducer = (String)params.get("introducer");
        String orderCode = (String)params.get("orderCode");
        String orderStatus = (String)params.get("orderStatus");
        String orderContractStatus = (String)params.get("orderContractStatus");
        String creatorList = (String)params.get("creatorList");


        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        wrapper.eq(StrUtil.isNotBlank(customerId), "customer_id", customerId);
        wrapper.like(StrUtil.isNotBlank(serviceItem), "service_item", serviceItem);
        wrapper.like(StrUtil.isNotBlank(introducer), "introducer", introducer);
        wrapper.like(StrUtil.isNotBlank(orderCode), "order_code", orderCode);
        wrapper.eq(StrUtil.isNotBlank(orderStatus), "order_status", orderStatus);
        wrapper.eq(StrUtil.isNotBlank(orderContractStatus), "order_contract_status", orderContractStatus);
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            wrapper.eq("creator", userDetail.getId());
        }
        if (StringUtils.isNotBlank(creatorList)) {
            wrapper.in("creator", creatorList.split(","));
        }
        return wrapper;
    }


    @Override
    public PageData<OrderDTO> orderPage(Map<String, Object> params) {
        log.info("订单分页");
        // 获取所有的用户信息
        List<SysUserDTO> userDtoList = sysUserService.getAll();

        String creatorName = (String)params.get("creatorName");
        if (StringUtils.isNotBlank(creatorName)) {
            String userIdList = userDtoList.stream().filter(e -> e.getRealName().contains(creatorName)).map(e -> e.getId().toString()).distinct().collect(Collectors.joining(","));
            if (StringUtils.isBlank(userIdList)) {
                return new PageData<OrderDTO>(Collections.EMPTY_LIST, 0);
            }
            params.put("creatorList", userIdList);
        }
        // 获取所有的客户信息
        List<CustomerInfoDTO> customerInfoDtoList = customerInfoService.getAll();
        PageData<OrderDTO> page = this.page(params);
        // 根据订单ID查询合同表记录
        List<Long> orderIdList = page.getList().stream().map(e -> e.getId()).distinct().collect(Collectors.toList());
        List<OrderContractDTO> orderContractDtoList = orderContractService.getContractListByOrderIdList(orderIdList);
        // 根据订单ID集合查询订单费用表
        List<OrderPaymentDTO> orderPaymentList = orderPaymentService.getOrderPaymentList(orderIdList);
        page.getList().forEach(e -> {
            CustomerInfoDTO customerInfoDto = customerInfoDtoList.stream().filter(cust -> cust.getId().compareTo(e.getCustomerId()) == 0).findFirst().orElse(null);
            e.setCustomerInfoDto(customerInfoDto);
            SysUserDTO creatorDto = userDtoList.stream().filter(user -> user.getId().compareTo(e.getCreator()) == 0).findFirst().orElse(null);
            e.setCreatorName(creatorDto == null ? "" : creatorDto.getRealName());
            SysUserDTO updaterDto = userDtoList.stream().filter(user -> user.getId().compareTo(e.getUpdater()) == 0).findFirst().orElse(null);
            e.setUpdaterName(updaterDto == null ? "" : updaterDto.getRealName());

            OrderContractDTO orderContractDto = orderContractDtoList.stream().filter(j -> j.getOrderId().compareTo(e.getId()) == 0).findFirst().orElse(null);
            if (orderContractDto != null) {
                e.setContractNumber(orderContractDto.getContractNumber());
                e.setSignedDate(orderContractDto.getSignedDate());
                if (StringUtils.isNotBlank(orderContractDto.getFilePath())) {
                    e.setFileDataList(JSON.parseArray(orderContractDto.getFilePath(), FileInfoDTO.class));
                } else {
                    e.setFileDataList(new ArrayList<FileInfoDTO>());
                }
                if (StringUtils.isNotBlank(orderContractDto.getImagePath())) {
                    List<FileInfoDTO> imageDataList = JSON.parseArray(orderContractDto.getImagePath(), FileInfoDTO.class);
                    e.setImageDataList(imageDataList);
                    e.setImageDataUrlList(imageDataList.stream().map(FileInfoDTO::getUrl).distinct().collect(Collectors.toList()));
                    e.setImageDataSize(imageDataList.size());
                } else {
                    e.setImageDataSize(0);
                }
            }
            // 报价图片存储路径
            List<FileInfoDTO> amountImagePathList = JSON.parseArray(e.getAmountImagePath(), FileInfoDTO.class);
            if (CollectionUtils.isNotEmpty(amountImagePathList)) {
                e.setAmountImagePathList(amountImagePathList);
                e.setAmountImageUrlList(amountImagePathList.stream().map(FileInfoDTO::getUrl).collect(Collectors.toList()));
                e.setAmountImagePathSize(amountImagePathList.size());
            } else {
                e.setAmountImagePathSize(0);
            }
            List<OrderPaymentDTO> filterPayList = orderPaymentList.stream().filter(pay -> pay.getOrderId().compareTo(e.getId()) == 0).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(filterPayList)) {
                // 已支付金额合计
                BigDecimal totalPayAmount = filterPayList.stream().map(OrderPaymentDTO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
                e.setTotalPayAmount(totalPayAmount);
                // 未支付金额合计
                BigDecimal totalUnPayAmount = e.getTotalAmount().subtract(totalPayAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                e.setTotalUnPayAmount(totalUnPayAmount);
                // 收款待审核项目
                e.setPayExamineNum(filterPayList.stream().filter(pay -> pay.getIsReceived() == 0).collect(Collectors.toList()).size());
            } else {
                e.setTotalPayAmount(new BigDecimal(0));
                e.setTotalUnPayAmount(new BigDecimal(0));
                e.setPayExamineNum(0);
            }
        });
        return page;
    }

    @Override
    public JSONObject getPayAndNoPayList(Map<String, Object> params) {
        log.info("统计已付、未付费用金额");
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        // 获取所有的用户信息
        List<SysUserDTO> userDtoList = sysUserService.getAll();
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            userDtoList = userDtoList.stream().filter(user -> user.getId().compareTo(userDetail.getId()) == 0).collect(Collectors.toList());
        }
        // 已付费用
        List<PayAndNoPayDTO> payList = this.getPayList(params, userDtoList);
        // 未付费用
        List<PayAndNoPayDTO> noPayList = this.getNoPayList(params, userDtoList);

        List<String> realNameList = new ArrayList<>();
        List<BigDecimal> totalPayList = new ArrayList<>();
        List<BigDecimal> totalNoPayList = new ArrayList<>();
        userDtoList.forEach(user -> {
            realNameList.add(user.getRealName());
            // 已付费用
            PayAndNoPayDTO payDto = payList.stream().filter(pay -> pay.getUserId().compareTo(user.getId()) == 0).findFirst().orElse(null);
            if (payDto != null) {
                totalPayList.add(payDto.getTotalPayAmount());
            } else {
                totalPayList.add(new BigDecimal(0));
            }
            // 未付费用
            PayAndNoPayDTO noPayDto = noPayList.stream().filter(pay -> pay.getUserId().compareTo(user.getId()) == 0).findFirst().orElse(null);
            if (payDto != null) {
                totalNoPayList.add(noPayDto.getTotalPayAmount());
            } else {
                totalNoPayList.add(new BigDecimal(0));
            }
        });
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("realNameList", realNameList);
        jsonObject.put("totalPayList", totalPayList);
        jsonObject.put("totalNoPayList", totalNoPayList);
        return jsonObject;
    }

    /**
     * 已付费用
     * @param params
     * @return
     */
    private List<PayAndNoPayDTO> getPayList(Map<String, Object> params, List<SysUserDTO> userDtoList) {
        // 获取所有的订单费用信息
        List<OrderPaymentDTO> allOrderPaymentList = orderPaymentService.getAllOrderPaymentList(params);
        List<OrderPaymentDTO> collect = allOrderPaymentList.stream().filter(e -> e.getIsReceived() == 1 && e.getIsExamine() == 1).collect(Collectors.toList());

        List<PayAndNoPayDTO> list = new ArrayList<>();
        userDtoList.forEach(user -> {
            // 用户ID
            Long userId = user.getId();
            // 姓名
            String realName = user.getRealName();
            // 过滤
            BigDecimal totalPayAmount = collect.stream().filter(e -> e.getCreator().compareTo(userId) == 0)
                    .map(OrderPaymentDTO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);

            PayAndNoPayDTO payAndNoPayDTO = new PayAndNoPayDTO();
            payAndNoPayDTO.setUserId(userId);
            payAndNoPayDTO.setRealName(realName);
            payAndNoPayDTO.setTotalPayAmount(totalPayAmount);
            list.add(payAndNoPayDTO);
        });
        return list;
    }

    /**
     * 未付费用
     * @param params
     * @return
     */
    private List<PayAndNoPayDTO> getNoPayList(Map<String, Object> params, List<SysUserDTO> userDtoList) {
        List<OrderContractDTO> allContractList = orderContractService.getAllContractList(params);
        List<Long> orderIdList = allContractList.stream().map(e -> e.getOrderId()).distinct().collect(Collectors.toList());
        // 获取订单费用信息
        List<OrderPaymentDTO> allOrderPaymentList = orderPaymentService.getOrderPaymentList(orderIdList);
        List<OrderPaymentDTO> collect = allOrderPaymentList.stream().filter(e -> e.getIsReceived() != 1 && e.getIsExamine() != 1).collect(Collectors.toList());

        List<PayAndNoPayDTO> list = new ArrayList<>();
        userDtoList.forEach(user -> {
            // 用户ID
            Long userId = user.getId();
            // 姓名
            String realName = user.getRealName();
            // 过滤
            BigDecimal totalNoPayAmount = collect.stream().filter(e -> e.getCreator().compareTo(userId) == 0)
                    .map(OrderPaymentDTO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);

            PayAndNoPayDTO payAndNoPayDTO = new PayAndNoPayDTO();
            payAndNoPayDTO.setUserId(userId);
            payAndNoPayDTO.setRealName(realName);
            payAndNoPayDTO.setTotalPayAmount(totalNoPayAmount);
            list.add(payAndNoPayDTO);
        });
        return list;
    }

    @Override
    public List<JSONObject> getEchartsPayList(Map<String, Object> params) {
        log.info("统计已完结订单金额和未完结订单待支付金额");
        List<JSONObject> list = new ArrayList<>();
        list.add(this.finishOrderPay(params));
        list.add(this.unFinishOrderPay(params));
        return list;
    }

    @Override
    public List<JSONObject> getEchartsOrderNumList(Map<String, Object> params) {
        log.info("统计已完结订单数量和未完结订单数量");
        List<JSONObject> list = new ArrayList<>();
        list.add(this.finishOrderNum(params));
        list.add(this.unFinishOrderNum(params));
        return list;
    }

    /**
     * 获取已完成的订单数量
     * @param params
     * @return
     */
    private JSONObject finishOrderNum(Map<String, Object> params) {
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());

        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", 1);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.between("create_date", startDate, endDate);
        }
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            wrapper.eq("creator", userDetail.getId());
        }
        List<OrderEntity> entityList = this.baseDao.selectList(wrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "已完成订单数量");
        jsonObject.put("value", entityList.size());
        return jsonObject;
    }

    /**
     * 获取未完成的订单数量
     * @param params
     * @return
     */
    private JSONObject unFinishOrderNum(Map<String, Object> params) {
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());

        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", 0);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.between("create_date", startDate, endDate);
        }
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            wrapper.eq("creator", userDetail.getId());
        }
        List<OrderEntity> entityList = this.baseDao.selectList(wrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "未完成订单数量");
        jsonObject.put("value", entityList.size());
        return jsonObject;
    }

    /**
     * 获取已完成的订单支付金额
     * @param params
     * @return
     */
    private JSONObject finishOrderPay(Map<String, Object> params) {
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());

        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", 1);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.between("create_date", startDate, endDate);
        }
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            wrapper.eq("creator", userDetail.getId());
        }
        List<OrderEntity> entityList = this.baseDao.selectList(wrapper);
        BigDecimal totalPayAmount = entityList.stream().map(OrderEntity::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "已完成订单-已支付金额总和");
        jsonObject.put("value", totalPayAmount);
        return jsonObject;
    }

    /**
     * 获取未完成的订单待支付金额
     * @param params
     * @return
     */
    private JSONObject unFinishOrderPay(Map<String, Object> params) {
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());

        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");

        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status", 0);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.between("create_date", startDate, endDate);
        }
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            wrapper.eq("creator", userDetail.getId());
        }
        List<OrderEntity> entityList = this.baseDao.selectList(wrapper);
        List<Long> orderIdList = entityList.stream().map(e -> e.getId()).distinct().collect(Collectors.toList());
        // 需要支付的金额合计
        BigDecimal totalPayAmount = entityList.stream().map(OrderEntity::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 根据订单ID集合查询订单费用表
        List<OrderPaymentDTO> orderPaymentList = orderPaymentService.getOrderPaymentList(orderIdList);
        // 已支付的金额合计
        BigDecimal totalPayedAmount = orderPaymentList.stream().map(OrderPaymentDTO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 待支付金额
        BigDecimal totalUnPayAmount = totalPayAmount.subtract(totalPayedAmount).setScale(2, BigDecimal.ROUND_HALF_UP);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "未完成订单-待支付金额总和");
        jsonObject.put("value", totalUnPayAmount);
        return jsonObject;
    }

    @Override
    public OrderDTO getOrder(Long id) {
        log.info("详情");
        OrderDTO data = this.get(id);
        OrderContractDTO orderContractDto = orderContractService.getByOrderId(id);
        if (orderContractDto != null) {
            data.setContractId(orderContractDto.getId());
            data.setContractNumber(orderContractDto.getContractNumber());
            data.setSignedDate(orderContractDto.getSignedDate());
            data.setFileDataList(JSON.parseArray(orderContractDto.getFilePath(), FileInfoDTO.class));
            data.setImageDataList(JSON.parseArray(orderContractDto.getImagePath(), FileInfoDTO.class));
        }
        data.setAmountImagePathList(JSON.parseArray(data.getAmountImagePath(), FileInfoDTO.class));
        if (data.getOrderContractStatus() == 0) {
            data.setContractFlag(false);
        } else {
            data.setContractFlag(true);
        }
        return data;
    }

    @Override
    public FileInfoDTO uploadFile(MultipartFile uploadFile) {
        log.info("批量上传文件");
        if(uploadFile == null) {
            // 判断文件是否为空
            throw new RenException("请再次上传文件！");
        }
        // 获取原文件名称
        String oldFileName = uploadFile.getOriginalFilename();
        // 获取后缀名
        String prefix = FilenameUtils.getExtension(oldFileName);
        // 对文件重新命名
        String uuid = UUID.randomUUID().toString();
        String newFileName = uuid + "." + prefix;
        try {
            // 判断文件夹是否存在，不存在则创建
            String filePath = DateUtils.format(new Date(), "yyyyMMdd");
            File targetFile = new File(this.path + this.uploadsPath + File.separator + filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            // 将文件写到服务器指定的文件
            String pathName = this.path + this.uploadsPath + File.separator + filePath + File.separator
                    + newFileName;
            File dest = new File(pathName);
            uploadFile.transferTo(dest);
            // 将图片名称和地址传出
            FileInfoDTO fileInfoDto = new FileInfoDTO();
            fileInfoDto.setName(filePath + "/" + oldFileName);
            fileInfoDto.setUrl(this.fileUrl + this.uploadsPath + "/" + filePath + "/" + newFileName);
            log.info("文件上传成功>{}", pathName);
            return fileInfoDto;
        } catch (IOException e) {
            log.error("文件上传异常:{}", ExceptionUtils.getStackTrace(e));
            throw new RenException("文件上传失败！");
        }
    }

    @Override
    public void orderSave(OrderDTO dto) {
        log.info("保存");
        // 获取当前系统时间
        long date = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String prefix = simpleDateFormat.format(new Date(date)) + "-CQ";
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<OrderEntity>();
        wrapper.orderByDesc("create_date");
        wrapper.last("LIMIT 1");
        OrderEntity order = this.baseDao.selectOne(wrapper);
        int lastOrderNum = 1;
        if (null != order) {
            lastOrderNum = Integer.parseInt(order.getOrderCode().substring(11));
            lastOrderNum++;
            if (lastOrderNum > 99999) {
                lastOrderNum = 1;
            }
        }
        // 订单编号
        String orderCodeNo = prefix + String.format("%05d", lastOrderNum);

        OrderEntity orderEntity = ConvertUtils.sourceToTarget(dto, OrderEntity.class);
        orderEntity.setOrderCode(orderCodeNo);
        // 是否签署合同状态判断
        if (CollectionUtils.isEmpty(dto.getImageDataList()) && CollectionUtils.isEmpty(dto.getFileDataList())) {
            orderEntity.setOrderContractStatus(0);
        } else {
            orderEntity.setOrderContractStatus(1);
        }
        if (CollectionUtils.isNotEmpty(dto.getAmountImagePathList())) {
            orderEntity.setAmountImagePath(JSONArray.toJSONString(dto.getAmountImagePathList()));
        }
        this.baseDao.insert(orderEntity);
        // 保存合同信息
        if (orderEntity.getOrderContractStatus() == 1) {
            OrderContractDTO orderContractDto = new OrderContractDTO();
            orderContractDto.setOrderId(orderEntity.getId());
            orderContractDto.setContractNumber(dto.getContractNumber());
            orderContractDto.setSignedDate(dto.getSignedDate());
            if (CollectionUtils.isNotEmpty(dto.getImageDataList())) {
                orderContractDto.setImagePath(JSONArray.toJSONString(dto.getImageDataList()));
            }
            if (CollectionUtils.isNotEmpty(dto.getFileDataList())) {
                orderContractDto.setFilePath(JSONArray.toJSONString(dto.getFileDataList()));
            }
            orderContractService.save(orderContractDto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderUpdate(OrderDTO dto) {
        log.info("修改");
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            throw new RenException("您暂无权限对订单进行修改!");
        }
        OrderEntity orderEntity = ConvertUtils.sourceToTarget(dto, OrderEntity.class);
        // 是否签署合同状态判断
        if (CollectionUtils.isEmpty(dto.getImageDataList()) && CollectionUtils.isEmpty(dto.getFileDataList())) {
            orderEntity.setOrderContractStatus(0);
        } else {
            orderEntity.setOrderContractStatus(1);
        }
        if (CollectionUtils.isNotEmpty(dto.getAmountImagePathList())) {
            orderEntity.setAmountImagePath(JSONArray.toJSONString(dto.getAmountImagePathList()));
        }
        this.baseDao.updateById(orderEntity);
        // 更新合同信息
        if (orderEntity.getOrderContractStatus() == 0) {
            orderContractService.deleteByOrderId(dto.getId());
        }
        if (orderEntity.getOrderContractStatus() == 1) {
            orderContractService.deleteByOrderId(dto.getId());
            OrderContractDTO orderContractDto = new OrderContractDTO();
            orderContractDto.setOrderId(orderEntity.getId());
            orderContractDto.setContractNumber(dto.getContractNumber());
            orderContractDto.setSignedDate(dto.getSignedDate());
            if (CollectionUtils.isNotEmpty(dto.getImageDataList())) {
                orderContractDto.setImagePath(JSONArray.toJSONString(dto.getImageDataList()));
            }
            if (CollectionUtils.isNotEmpty(dto.getFileDataList())) {
                orderContractDto.setFilePath(JSONArray.toJSONString(dto.getFileDataList()));
            }
            orderContractService.save(orderContractDto);
        }
    }

    @Override
    public void signContract(OrderDTO dto) {
        log.info("补签合同");
        OrderEntity orderEntity = ConvertUtils.sourceToTarget(dto, OrderEntity.class);
        // 是否签署合同状态判断
        if (CollectionUtils.isEmpty(dto.getImageDataList()) && CollectionUtils.isEmpty(dto.getFileDataList())) {
            orderEntity.setOrderContractStatus(0);
        } else {
            orderEntity.setOrderContractStatus(1);
        }
        this.baseDao.updateById(orderEntity);
        // 更新合同信息
        if (orderEntity.getOrderContractStatus() == 0) {
            orderContractService.deleteByOrderId(dto.getId());
        }
        if (orderEntity.getOrderContractStatus() == 1) {
            orderContractService.deleteByOrderId(dto.getId());
            OrderContractDTO orderContractDto = new OrderContractDTO();
            orderContractDto.setOrderId(orderEntity.getId());
            orderContractDto.setContractNumber(dto.getContractNumber());
            orderContractDto.setSignedDate(dto.getSignedDate());
            if (CollectionUtils.isNotEmpty(dto.getImageDataList())) {
                orderContractDto.setImagePath(JSONArray.toJSONString(dto.getImageDataList()));
            }
            if (CollectionUtils.isNotEmpty(dto.getFileDataList())) {
                orderContractDto.setFilePath(JSONArray.toJSONString(dto.getFileDataList()));
            }
            orderContractService.save(orderContractDto);
        }
    }

    @Override
    public void finishOrder(OrderDTO dto) {
        log.info("订单完结");
        dto.setOrderStatus(1);
        dto.setFinishDate(new Date());
        this.update(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderDelete(Long[] ids) {
        log.info("删除");
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());

        for (Long id : ids) {
            OrderEntity orderEntity = this.selectById(id);
            if (orderEntity.getOrderStatus() == 1 && !officeRole) {
                throw new RenException("已完结订单不允许删除！");
            }
            this.deleteById(id);
            orderContractService.deleteByOrderId(id);
            orderPaymentService.deleteByOrderId(id);
        }
    }

    @Override
    public List<OrderExcel> exportList(Map<String, Object> params) {
        log.info("导出");
        List<OrderExcel> excelList = new ArrayList<>();
        // 获取所有的用户信息
        List<SysUserDTO> userDtoList = sysUserService.getAll();
        // 获取所有的客户信息
        List<CustomerInfoDTO> customerInfoDtoList = customerInfoService.getAll();

        List<OrderEntity> entityList = this.baseDao.selectList(this.getWrapper(params));
        List<Long> orderIdList = entityList.stream().map(e -> e.getId()).distinct().collect(Collectors.toList());
        // 根据订单ID集合查询订单费用表
        List<OrderPaymentDTO> orderPaymentList = orderPaymentService.getOrderPaymentList(orderIdList);
        entityList.forEach(e -> {
            CustomerInfoDTO customerInfoDto = customerInfoDtoList.stream().filter(cust -> cust.getId().compareTo(e.getCustomerId()) == 0).findFirst().orElse(null);
            OrderExcel orderExcel = new OrderExcel();
            // 订单编号
            orderExcel.setOrderCode(e.getOrderCode());
            // 接单时间
            orderExcel.setCreateDate(e.getCreateDate());
            // 公司名称
            orderExcel.setCompanyName(customerInfoDto.getCompanyName());
            // 服务项目
            orderExcel.setServiceItem(e.getServiceItem());
            // 介绍人
            orderExcel.setIntroducer(e.getIntroducer());
            // 签约人/办事人
            SysUserDTO creatorDto = userDtoList.stream().filter(user -> user.getId().compareTo(e.getCreator()) == 0).findFirst().orElse(null);
            orderExcel.setCreatorName(creatorDto == null ? "" : creatorDto.getRealName());
            // 订单总金额
            orderExcel.setTotalAmount(e.getTotalAmount());
            // 订单成本
            orderExcel.setCostAmount(e.getCostAmount());

            List<OrderPaymentDTO> filterPayList = orderPaymentList.stream().filter(pay -> pay.getOrderId().compareTo(e.getId()) == 0).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(filterPayList)) {
                // 已支付金额合计
                BigDecimal totalPayAmount = filterPayList.stream().map(OrderPaymentDTO::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
                orderExcel.setTotalPayAmount(totalPayAmount);
                // 未支付金额合计
                BigDecimal totalUnPayAmount = e.getTotalAmount().subtract(totalPayAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                orderExcel.setTotalUnPayAmount(totalUnPayAmount);
            } else {
                orderExcel.setTotalPayAmount(new BigDecimal(0));
                orderExcel.setTotalUnPayAmount(new BigDecimal(0));
            }
            excelList.add(orderExcel);
        });
        return excelList;
    }

    @Override
    public List<OrderDTO> getOrderByCustomerIdList(List<Long> customerIdList) {
        log.info("根据客户ID查询订单");
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<OrderEntity>();
        wrapper.in("customer_id", customerIdList);
        List<OrderEntity> entityList = this.baseDao.selectList(wrapper);
        return ConvertUtils.sourceToTarget(entityList, OrderDTO.class);
    }

}